package com.prueba.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;


import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.SpaceSummary;

import org.xwiki.xmlrpc.model.XWikiPageSummary;




import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.prueba.client.servicios.PlanerService;
import com.prueba.compartido.*;
import com.prueba.server.Conector;
import com.prueba.server.Pagina;

/**
 * The server side implementation of the RPC service.
 * TODO: Implement pending methods
 */
@SuppressWarnings("serial")
public class PlanerServiceImpl extends RemoteServiceServlet implements
    PlanerService {
  @Override
  public Collection<Void> actualizarVista(String nombreVista, int nivelNuevo)
      throws ServerException {  
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<Void> documentarSeccion(String nombreVista,
      String nombreSeccion, boolean documentada) throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<Accion> ejecutarSolver()
      throws ServerException { 
	  
	  return null;
	  
  }
  

  @Override
  public int getCostoIteracion() throws ServerException {
    // TODO Auto-generated method stub
    return 0;
  }

  @Override
  public Preferencia getPreferencia(String nombreStakeholder, String nombreVista)
      throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

 /* @Override
  public Seccion getSeccion(String nombreVista, String nombreSeccion)
      throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }*/

  @Override
  public Stakeholder getStakeholder(String nombreStakeholder)
      throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Vista getVista(String nombreVista) throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public void savePreferencia(Preferencia preferencia) throws ServerException {
    // TODO Auto-generated method stub
  }

 /* @Override
  public void saveSeccion(Seccion seccion) throws ServerException {
    // TODO Auto-generated method stub
  }*/
  
  //Servicio para borrar un stakeholder de la base de datos:
  @Override
  public  void deleteStakeholder(Long id){
	  System.out.println("Intentando borrar Stakeholder con id: "+id);
	  PersistenceManager pm = PMF.getInstance().get().getPersistenceManager();
	  
	  
	  Query query = pm.newQuery("SELECT FROM " + Stakeholder.class.getName() +" WHERE this.id == " + id);
	  Long number = (Long)query.deletePersistentAll();
	  System.out.println(number);	  
	  
	 /* 
	  Stakeholder sta = (Stakeholder) pm.getObjectById(id);  // Retrieves the object to delete
	  pm.deletePersistent(sta);*/
	  
  }
  
  //Servicio para agregar un stakeholder a la base de datos:
  @Override
  public void saveStakeholder(Stakeholder stakeholder) throws ServerException {
	  PersistenceManager pm = PMF.getInstance().get().getPersistenceManager();
	    Transaction tx = null;
	    try {
	      //Si no existe (nunca le fue asignado un id) , lo creamos:	
	      if (stakeholder.getId() == null) {
	        pm.makePersistent(stakeholder);
	      } else {
	    	//Sino lo modificamos:  
	        tx = pm.currentTransaction();
	        tx.begin();
	        Stakeholder currentStakeholder = pm.getObjectById(Stakeholder.class, stakeholder.getId());
	        currentStakeholder.setPrioridad(stakeholder.getPrioridad());
	        currentStakeholder.setCantidad(stakeholder.getCantidad());
	        currentStakeholder.setNombreStakeholder(stakeholder.getNombreStakeholder());
	        tx.commit();}
	       }catch (Exception e) {
	          // You shouldn't catch generic "Exception"s.
	          // But AppEngine (actually DataNucheus) may throw a wide set of
	          // exceptions and I couldn't find the specification of all possible
	          // exceptions in AppEngine documentation.
	          throw new ServerException("Error guardando stakeholder: " + e.getMessage());
	        } finally {
	          if (tx != null && tx.isActive()) {
	            tx.rollback();
	          }
	          pm.close();
	        }
  }

  @Override
  public void saveVista(Vista vista) throws ServerException {
    // TODO Auto-generated method stub
  }

  @Override
  public void setCostoIteracion(int costo) throws ServerException {
    // TODO Auto-generated method stub
    
  }

  @Override
  public Collection<Preferencia> getPreferencias() throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Vector<SeccionSinFormato> getSeccions(String dirPagina) throws ServerException {  
	
	Pagina pagina = Conector.getInstance().getPagina(dirPagina);
	return pagina.generarToc();
	
  }

  @Override
  @SuppressWarnings("unchecked")
  public Collection<Stakeholder> getStakeholders() throws ServerException {
	  List<Stakeholder> matchedContacts = new ArrayList<Stakeholder>();
	    
	    PersistenceManager pm = PMF.getInstance().get().getPersistenceManager();  
	    try {
	      String query = "select from " + Stakeholder.class.getName();
	      List<Stakeholder> tasks = (List<Stakeholder>)pm.newQuery(query).execute();
	 
	      for (Stakeholder task: tasks) {
	        //if (folder == null || task.getFolder().equals(folder)) Esto va a servir para preguntar por los stakeholders del usuario logeado.
	          matchedContacts.add(task);
	      }
	    } catch (Exception e) {
	      throw new ServerException("Error leyendo stakeholders: " + e.getMessage());
	    } finally {
	      pm.close();
	    }
	    return matchedContacts;
  }

  @Override
  public Collection<Vista> getVistas() throws ServerException {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
	public Boolean logearUsuario(String usuario, String password)  {
		Boolean logeado = false;
		try {
			logeado = Conector.getInstance().Conectarse("http://localhost:8080/xwiki/xmlrpc/confluence",usuario,password);
		} catch (MalformedURLException e) {
			System.out.println("Error intentando conectarse a XWiki");
		}
		return logeado;
	}
	
	@Override
	public Collection<Espacio> getEspacios() {
		Collection<SpaceSummary> espacios = null;
		try {
			espacios = Conector.getInstance().getEspacios();
		} catch (XmlRpcException e) {
			System.out.println("Fallo a la hora de obtener espacios del rpc.");
		}
		
		Collection<Espacio> resultado = new ArrayList<Espacio>();
		
		Iterator<SpaceSummary> it = espacios.iterator();
		while(it.hasNext())
		{
			SpaceSummary aux = it.next();
				if(!aux.getName().startsWith("$")){
					String nombreEspacio = aux.getName();
					List<XWikiPageSummary> auxPaginas = null;
					try {
						auxPaginas = Conector.getInstance().getRpc().getPages(aux);
					} catch (XmlRpcException e) {
						// TODO Ver que poner en este error
						e.printStackTrace();
					}
					Iterator<XWikiPageSummary> itPaginas = auxPaginas.iterator();
					List<String> paginasEspacio = new Vector<String>();
					while(itPaginas.hasNext()){
						XWikiPageSummary pagina = itPaginas.next();
						String nombrePagina=pagina.getTitle();
						if(pagina.getTitle().equals(nombreEspacio))
						nombrePagina="WebHome";
						paginasEspacio.add(nombrePagina);
					}
					System.out.println("Espacio-"+nombreEspacio);
					
					resultado.add(new Espacio(nombreEspacio,paginasEspacio));
				}
		}
		
		return resultado;
	}
	
	@Override
	public Collection<String> testServlet() {
		try { 
	
	        String linea;
	        Process p = Runtime.getRuntime().exec("\"D:/XWikiDisenio/bin 2/bin 2/migracion.bat\"");
	        BufferedReader input = new BufferedReader (new InputStreamReader (p.getInputStream()));
	      
	         
	        //De aqui tomo lo que va mostrando el ms-dos
	        linea = input.readLine();
	        while(linea!=null)
	       {
	          System.out.println(linea);
	          linea = input.readLine();
	       }
	
	  
	           input.close(); 
	    }catch (Exception err) { 
	           System.out.println("Error ejecutando .bat"); 
	    } 
		try { 
	        String linea;
	        Process p = Runtime.getRuntime().exec("\"D:/XWikiDisenio/bin 2/bin 2/migracion.bat\"");
	        BufferedReader input = new BufferedReader (new InputStreamReader (p.getInputStream()));
	        p.waitFor();
	        
	        System.out.println("Empezando a mostrar lineas: ");
	        while ((linea = input.readLine()) != null) { 
	             System.out.println(linea); 
	         } 
	           input.close(); 
	    }catch (Exception err) { 
	           System.out.println("Error ejecutando .bat"); 
	    } 
		
		
	
	
		return null;
		}
	
	@Override
	public HashMap<String, String> getConfDoc(String dirXML) {
		ParserXML parXML = new ParserXML();
		return parXML.getConfiguracion("C:/Documents and Settings/Paisa/Escritorio/Secciones.xml");
	}
	
	@Override
	public void setConfDoc(HashMap<String,String> conf) {
		ParserXML parXML = new ParserXML();
		parXML.setConfiguracion(conf);
	}

}
